const createError = require('http-errors');
const express = require('express');
const path = require('path');
// const fs = require('fs');
const app = express()
const PORT = process.env.PORT || 4000;
const routers = require('./routes/index');


app.set('view engine', 'html');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

// 白名单
const whiteList = ['http://localhost:8080','http://localhost:8081','http://192.168.1.2:8080','http://192.168.0.108:8080','http://localhost:3000']
app.all('/api/*', function (req, res, next) {
    if(req.headers.origin && whiteList.includes(req.headers.origin.toLowerCase())){
        res.header("Access-Control-Allow-Origin", req.headers.origin || "")
    }
    // 允许自定义请求头
    res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept,token,userId");
    // 允许请求方式
    res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Content-Type", "application/json;charset=utf-8");
    // 处理css文件加载无法正常执行
    if(req.headers.accept.indexOf('text/css') !== -1){
        res.header("Content-Type", "text/css;charset=utf-8");
    }
    next();
});

routers.forEach(route => {
    app.use('/api', route);
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

app.listen(PORT, () => {
    console.log(`Node Express server listening on http://localhost:${PORT}`);
});